package com.aaa.bookproject.config;

import com.aaa.bookproject.entity.TLogin;
import com.aaa.bookproject.service.ITLoginService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;

import javax.annotation.Resource;
import java.util.Set;

/**
 * Realm充当了Shiro与应用安全数据连接时的桥梁
 * 当用户进行登录认证与授权的时候，
 * shiro会从配置的Realm类中查找到对应的用户及其权限信息
 *
 * @author ：YongQi Lv
 * @date ：2021/4/28 14:34
 */
public class UserRealm extends AuthorizingRealm {

    @Resource
    private ITLoginService loginService;

    /**
     * 用于用户授权的方法
     * @param principalCollection
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        // 获取当前操作的主体
        Subject subject = SecurityUtils.getSubject();
        // 获取当前登录用户的信息
        TLogin tLogin = (TLogin) subject.getPrincipal();
        // 获取当前接口的实现类
        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
        // 查询用户对用的角色信息和拥有的资源文件
        Set<String> roles = loginService.getRoleidByStaffid(tLogin.getStaffid());
        simpleAuthorizationInfo.setRoles(roles);
        Set<String> menus = loginService.getMenusByStaffid(tLogin.getStaffid());
        simpleAuthorizationInfo.setStringPermissions(menus);
        // 返回数据
        return simpleAuthorizationInfo;
    }

    /**
     * 用户登录验证
     * @param authenticationToken
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        UsernamePasswordToken usernamePasswordToken = (UsernamePasswordToken) authenticationToken;
        // 获取登录的用户名
        String username = usernamePasswordToken.getUsername();
        // 通过用户名去数据库查询是否存在该用户
        QueryWrapper<TLogin> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("loginid",username);
        TLogin one = loginService.getOne(queryWrapper);
        // 进行判断
        if (one == null ){
            return null;
        }
        // 数据库存在，进行密码验证
        return new SimpleAuthenticationInfo(one,one.getLoginpsw(),"");

    }
}
